package com.efounder.form.model;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.DataSetListener;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.json.JSONUtil;
import com.efounder.common.TCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.DMComponent;
import com.efounder.form.DataSetComponent;
import com.efounder.form.EFFormDataModel;
import com.efounder.form.base.DataComponent;
import com.efounder.form.base.IComponent;
import com.efounder.form.builder.IScriptObject;
import com.efounder.form.service.JSONFormModelLoadService;
import com.efounder.form.util.JsonEFDataSetUtil;
import com.efounder.frame.baseui.EFActivity;
import com.efounder.mobilecomps.R;
import com.efounder.service.IService;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.LogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Javor on 16/9/3.
 */

public class JSONFormModel extends DataComponent implements IComponent, DataSetComponent, DataSetListener, IScriptObject {
    public JSONFormModel() {
    }

    private String id;
    //数据模型
    private EFFormDataModel formDataModel = new EFFormDataModel();
    //扩展属性模型
    private EFFormDataModel formExtModel = new EFFormDataModel();

    private List<DMComponent> dmCompList;

    private String billDataSetID;

    public IService getSaveService() {
        return saveService;
    }

    public void setSaveService(IService saveService) {
        this.saveService = saveService;
    }

    public IService getLoadService() {
        return loadService;
    }

    public void setLoadService(IService loadService) {
        this.loadService = loadService;
    }

    public void setLoadService(JSONFormModelLoadService loadService) {
        this.loadService = loadService;
    }

    private IService saveService;
    private IService loadService;

    private Map scriptObject = new HashMap();
    private Map scriptContext = new HashMap();

    public void setActiveDataSet(final EFDataSet dataSet) {
        if (dataSet == null) return;
        if (dmCompList == null || dmCompList.size() == 0) return;
        //if (dataSet.getTableName().equals(comp.getDataSetID())) {
// }
        for (final DMComponent comp : dmCompList)
            AppContext.getCurrentActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (comp.getDataSetID().equals(dataSet.getTableName())) {
                        comp.setDataSet(dataSet);
                    }
                }
            });
    }

    public void load() {
//        DialogUtils.showProgressDialog();

//        EFDataSet dataSet = new EFDataSet();
//        dataSet.setTableName("A");
//
//        EFRowSet rowSet = new EFRowSet();
//        rowSet.put("a","1");
//
//        dataSet.addRowSet(rowSet);
//
//        this.formDataModel.setBillDataSet(dataSet);
//        setActiveDataSet(this.formDataModel.getBillDataSet());


        requestDataSetData();


        //fixme 0412
//        new Thread() {
//
//            @Override
//            public void run() {
//                super.run();
//
//                if (loadService == null) return;
//                EFRowSet rowSet = (EFRowSet) loadService.executeService(null, null, null, null, null);
//                if (rowSet == null) return;
//                if (rowSet.getDataSetMap() == null) return;
//                formDataModel.setDataSetMap(rowSet.getDataSetMap());
//
//                if (billDataSetID == null) {
//                    HashMap<String, EFDataSet> map = formDataModel.getDataSetMap();
//                    for (String key : map.keySet()) {
//                        setActiveDataSet(map.get(key));
////                break;
//                    }
//                } else {
//                    formDataModel.setBillDataSet(formDataModel.getDataSetMap().get(billDataSetID));
//                    addFormModelDataSetListener(formDataModel);
//                    setActiveDataSet(formDataModel.getBillDataSet());
//                }
//                AppContext.getCurrentActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        FormAppUtil.executeCompScripts(JSONFormModel.this, scriptContext, "dataLoaded", null);
//                    }
//                });
//            }
//        }.start();


    }


    public void requestDataSetData() {

        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, String> modeIdMap = new HashMap<>();

        map.put("params", modeIdMap);
        ModelContainer modelContainer = (ModelContainer) this.dataContainer;
        if (modelContainer != null) {
            String nodeid = (String) modelContainer.getValue("NODE_ID", "");
            String GUID = (String) modelContainer.getValue("GUID", "");
            String FLOW_ID = (String) modelContainer.getValue("FLOW_ID", "");
            String MDL_ID = (String) modelContainer.getValue("MDL_ID", "");
            modeIdMap.put("NODE_ID", nodeid);
            modeIdMap.put("GUID", GUID);
            modeIdMap.put("FLOW_ID", FLOW_ID);
            modeIdMap.put("MDL_ID", MDL_ID);
        }


        final JSONObject jsonObject = new JSONObject(map);
        String json = jsonObject.toJSONString();
        LogUtils.i(json);
        ((EFActivity) AppContext.getCurrentActivity()).showLoading(ResStringUtil.getString(R.string.common_text_loading));

//        OSPTaskURL=https://cwyth-uat.cscec.com/OSPFlowCenter
        //"https://cwyth-uat.cscec.com/FIService/rest/load/loadform"
        String taskURL = EnvironmentVariable.getProperty("OSPTaskURL");
        if (taskURL.length() > 0) {
            taskURL = taskURL.substring(0, taskURL.lastIndexOf("/"));
            taskURL = taskURL + "/FIService/rest/load/loadform";
        }

        TCommonRequestManager.getInstance(AppContext.getInstance()).
                requestPostByAsyncWithJSON(AppContext.getCurrentActivity().getClass().getSimpleName(),
                        taskURL, json, new TCommonRequestManager.ReqCallBack<String>() {
                            @Override
                            public void onReqSuccess(String result) {
                                ((EFActivity) AppContext.getCurrentActivity()).dismissLoading();
                                EFDataSet efDataSet = null;
                                try {
                                    org.json.JSONObject jsonObject1 =  new org.json.JSONObject(result);
                                    org.json.JSONObject responseObjectObject = jsonObject1.getJSONObject("data")
                                            .getJSONObject("responseObject");
                                    efDataSet = JsonEFDataSetUtil.json2EFDataSet(responseObjectObject.toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (efDataSet != null) {
                                    formDataModel.setBillDataSet(efDataSet);
                                    setChildDataSet(efDataSet);
                                } else {
                                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_data_fail);
                                }
                            }

                            @Override
                            public void onReqFailed(String errorMsg) {
                                ((EFActivity) AppContext.getCurrentActivity()).dismissLoading();
                                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                            }
                        });
    }

    private void setChildDataSet(EFDataSet efDataSet) {
        if (efDataSet == null) {
            return;
        }
        setActiveDataSet(efDataSet);
        List<EFRowSet> efRowSetList = efDataSet.getRowSetArray();
        if (efRowSetList == null) {
            return;
        }
        for (int i = 0; i < efRowSetList.size(); i++) {
            EFRowSet efRowSet = efRowSetList.get(i);
            HashMap<String, EFDataSet> map = efRowSet.getDataSetMap();
            if (map == null) {
                continue;
            }
            for (String key : map.keySet()) {
                setChildDataSet(map.get(key));
            }
        }

    }


    /**
     * 将模型转成Datajson
     *
     * @return
     */
    public String convert2DataJSON() {
        return JSONUtil.RowSet2JSON(formDataModel, true);
    }

    /**
     * 将模型转成Extjson
     *
     * @return
     */
    public String convert2ExtJSON() {
        return JSONUtil.RowSet2JSON(formDataModel, true);
    }

    /**
     * 将json转换成模型
     *
     * @param dataJSON
     * @param extJSON
     */
    public void toModel(String dataJSON, String extJSON) {
        //formDataModel.setBillDataSet(JSONUtil.JSON2RowSet(dataJSON));
        // formExtModel.setBillDataSet(JSONUtil.JSON2DataSet(extJSON));
//        this.setActiveDataSet(formDataModel.getBillDataSet());
    }

    protected void addFormModelDataSetListener(EFFormDataModel formDataModel) {
        EFDataSet dataSet = formDataModel.getBillDataSet();
        if (dataSet != null)
            dataSet.addDataSetListener(this);
    }

    @Override
    public String getID() {
        return id;
    }

    @Override
    public void setID(String id) {
        this.id = id;
    }

    @Override
    public void creationComplete() {


        load();

        //数据保存到本地
//        String json = this.convert2DataJSON();
//        FileUtils.writeTextFile(Constants.RES_DIR +"/qrd.json", json);

        //数据从本地读取
//        String json1 = FileUtils.readTextFile(EFAppAccountUtils.getAppAccountJsonPath() +"/qrd.json");
//        EFRowSet rowSet = JSONUtil.JSON2RowSet(json1);
//        this.formDataModel.setDataSetMap(rowSet.getDataSetMap());
//        load();
    }

    @Override
    public void dataSetChanged(DataSetEvent event) {
        for (DMComponent comp : dmCompList) {
            if(event.getDataSet().getTableName() == comp.getDataSetID()){
                comp.dataSetChanged(event);
            }
        }
    }


    @Override
    public void insertDMComponent(DMComponent dmComponent) {
        if (dmCompList == null) {
            dmCompList = new ArrayList<DMComponent>();
        }
        dmCompList.add(dmComponent);
    }

    @Override
    public void removeDMComponent(DMComponent dmComponent) {

    }

    @Override
    public List<DMComponent> getDmCompList() {
        return dmCompList;
    }

    @Override
    public void setDmCompList(List<DMComponent> value) {
        this.dmCompList = value;
    }

    @Override
    public EFDataSet getDataSet(String dataSetKey) {
        return null;
    }

    @Override
    public List<String> getDataSetKey() {
        return null;
    }

    @Override
    public List<String> getDOMetaData(String obj_id) {
        return null;
    }

    @Override
    public Object loadByParam(Object param, Object userObject) {
        load();

        return null;
    }

    public EFFormDataModel getFormDataModel() {
        return formDataModel;
    }

    public void setFormDataModel(EFFormDataModel formDataModel) {
        this.formDataModel = formDataModel;
    }

    public String getBillDataSetID() {
        return billDataSetID;
    }

    public void setBillDataSetID(String billDataSetID) {
        this.billDataSetID = billDataSetID;
    }

    @Override
    public Map getScriptObject() {
        return scriptObject;
    }

    @Override
    public void setScriptObject(Map scriptObject) {
        this.scriptObject = scriptObject;
    }

    @Override
    public String getEventScript(String key) {
        return (String) scriptObject.get(key);
    }

    @Override
    public void setEventScript(String key, String script) {
        scriptObject.put(key, script);
    }

    @Override
    public Map getScriptContext() {
        return scriptContext;
    }

    @Override
    public void setScriptContext(Map context) {
        scriptContext = context;
    }
}
